<!DOCTYPE html>
<link rel=author href="mailto:jarhar@chromium.org">
<link rel=help href="https://bugs.chromium.org/p/chromium/issues/detail?id=1422275">
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<script src="/resources/testdriver.js"></script>
<script src="/resources/testdriver-vendor.js"></script>
<script src="/resources/testdriver-actions.js"></script>

<select style="appearance:base-select">
  <button>button</button>
  <datalist>
    <option class=one>one</option>
    <option class=two>two</option>
  </datalist>
</select>

<script>
const select = document.querySelector('select');
const datalist = document.querySelector('datalist');
const firstOption = document.querySelector('option.one');
const secondOption = document.querySelector('option.two');

promise_test(async () => {
  datalist.showPopover();
  assert_true(datalist.matches(':popover-open'));
  datalist.hidePopover();
  assert_false(datalist.matches(':popover-open'));
}, 'showPopover and hidePopover should work on the select datalist.');

promise_test(async () => {
  await test_driver.bless();
  select.showPicker();
  assert_true(datalist.matches(':popover-open'));
  datalist.hidePopover();
}, 'showPicker should show the select datalist.');

promise_test(async () => {
  datalist.addEventListener('beforetoggle', event => {
    event.preventDefault();
  }, {once: true});
  await test_driver.bless();
  select.showPicker();
  assert_false(datalist.matches(':popover-open'));
}, 'preventDefault on beforetoggle should prevent the datalist from showing.');

promise_test(async () => {
  select.remove();
  assert_throws_dom('InvalidStateError', () => datalist.showPopover());
  assert_false(datalist.matches(':popover-open'));
  document.body.appendChild(select);
}, 'showPopover on a disconnected datalist should throw an exception.');

promise_test(async () => {
  datalist.addEventListener('beforetoggle', event => {
    select.remove();
  }, {once: true});
  await test_driver.bless();
  select.showPicker();
  assert_false(!!select.parentNode);
  assert_false(datalist.matches(':popover-open'));
  document.body.appendChild(select);
}, 'Disconnecting while internally showing the datalist should not crash or show the popover.');

promise_test(async () => {
  datalist.showPopover();
  datalist.addEventListener('beforetoggle', event => {
    select.remove();
  }, {once: true});
  await test_driver.click(secondOption);
  assert_false(!!select.parentNode);
  assert_false(datalist.matches(':popover-open'));
  document.body.appendChild(select);
}, 'Disconnecting while internally hiding the datalist should not crash.');
</script>
